const fs = require('fs');
const path = require('path');

class FileUtils {
  static travelFile(dir, callBack) {
    fs.readdirSync(dir).forEach((file) => {
      var pathname = path.join(dir, file);
      console.log(pathname);
      if (fs.statSync(pathname).isDirectory()) {
        travelFile(pathname, callBack);
      } else {
        callBack(pathname);
      }
    });
  }

  static lsDirTree(path) {
    let base = {};
    let dirList = fs.readdirSync(path);

    if (!fs.statSync(path).isFile()) {
    } else {
    }
  }

  static setUpPageFile() {
    const path = require('path');
    const fs = require('fs');
    let mpath = path.join(require('os').homedir(), 'Desktop/feasy.page');

    fs.access(mpath, (err) => {
      if (err) {
        fs.writeFile(mpath, '', 'utf8', function (error) {
          console.log('写入成功');
        });
      }
    });

    fs.open(mpath, 'a', function (err, fd) {
      if (err) {
        throw err;
      }
      fs.fchmod(fd, '0777', function (err) {
        if (err) {
          throw err;
        }
        fs.close(fd, function () {
          console.log('Done');
        });
      });
    });
  }

  static readFile(mpath) {
    mpath = path.join(require('os').homedir(), 'Desktop/feasy.page');
    return fs.readFileSync(mpath, { encoding: 'utf-8' }).toString();
  }

  static saveFile(str, mpath) {
    mpath = path.join(require('os').homedir(), 'Desktop/feasy.page');
    const wfs = fs.createWriteStream(mpath, { encoding: 'utf-8' });
    if (typeof str !== 'string') {
      str = JSON.stringify(str);
    }
    wfs.write(str);
  }
}

module.exports = FileUtils;
